import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Drawer, message, Popconfirm } from 'antd';
import { useRequest } from 'umi';
import OrderForm from './OrderForm'; // 引入表单组件
import { fetchOrderList, deleteOrder,updateAudit, fetchOrderDetail } from '@/services/ant-design-pro/order'; // 假设你已经定义了这些服务

const OrderList: React.FC = () => {
  const actionRef = useRef();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [isEditMode, setIsEditMode] = useState(false);
  const [activeKey, setActiveKey] = useState<string>('');

  const { run: deleteRun } = useRequest(deleteOrder, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      actionRef.current?.reload();
    },
    onError: () => {
      message.error('删除失败');
    },
  });
const handleAudit = async (id: number) => {
  try {
    await updateAudit(id);
    message.success('审核成功');
    actionRef.current?.reload();
  } catch (error) {
    // message.error('审核失败');
    console.log('审核失败')
  }
  };
  const columns = [
    { title: '订单编码',width:150, dataIndex: 'orderCode',ellipsis:true },
    { title: '姓名', dataIndex: 'userName' },
    { title: '手机号', dataIndex: 'mobile' ,ellipsis:true },
    { title: '账户类型', dataIndex: 'accountType', valueEnum: { 0: '个人', 1: '企业'} },
    { title: '公司名称', dataIndex: 'companyName',  ellipsis:true },
    { title: '产品名称', dataIndex: 'orderName', search:false,ellipsis:true },
    { title: '订单原金额', dataIndex: 'originalAmount', valueType: 'money',search:false },
    { title: '修改金额', dataIndex: 'orderAmount', valueType: 'money' ,search:false },
    { title: '下单时间', dataIndex: 'orderTime',ellipsis:true,valueType: 'dateTime' },
    { title: '审核状态', dataIndex: 'auditStatus', valueEnum: { 20: '待审核', 21: '已审核', 22: '已驳回' } ,search:false },
    { title: '订单状态',search:false, dataIndex: 'orderStatus', valueEnum: { 0: '待支付', 1: '已完成', 2: '已取消',3:'待退款',4:'已退款',5:'改价失败',6:'订单超时失败',7:'退款失败' } },
    { title: '支付方式', dataIndex: 'payType', valueEnum: { 0: '支付宝', 1: '微信',2:'对公支付' ,3:'免费' } },
   
    {
      title: '操作',
      fixed: 'right',
      width: 120,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit" onClick={() => handleEdit(record)}>查看</a>,
        // <Popconfirm key="delete" title="确定删除该订单吗？" onConfirm={() => handleDelete(record.id)}>
        //   <a>删除</a>
        // </Popconfirm>,
      
        record.payType === '2' && record.orderStatus === 0 && (
          <>
          <Popconfirm key="audit" title="请确认订单是否到账" onConfirm={() => handleAudit(record.id)}>
            <a>审核</a>
          </Popconfirm>
          </>
)
      ],
    },
  ];

  const handleEdit = async (record) => {
    console.log(record,'record')
   const deatil =  await fetchOrderDetail(record.id)
    setCurrentRow(deatil.data);
    setIsEditMode(true);
    setDrawerVisible(true);
  };

  const handleDelete = (id) => {
    deleteRun(id);
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setCurrentRow(null);
    setIsEditMode(false);
  };

  return (
    <PageContainer header={{title:''}}>
      <ProTable
      scroll={{ x: 1500 }}
        actionRef={actionRef}
        rowKey="id"
        request={ (params) => fetchOrderList({...params, orderStatus: activeKey})}
        columns={columns}
        toolBarRender={() => [
          // <Button key="add" type="primary" onClick={() => setDrawerVisible(true)}>
          //   添加订单
          // </Button>,
        ]}

        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: "", label: <span>全部</span> },
              { key: "0", label: <span>待支付</span> },
              { key: "1", label: <span>已完成</span> },
              { key: "2", label: <span>已取消</span> },
              { key: "3", label: <span>待退款</span> },
              { key: "4", label: <span>已退款</span> },
              { key: "5", label: <span>改价失败</span> },
              { key: "6", label: <span>订单超时失效</span> },
              { key: "7", label: <span>退款失败</span> },
              
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
      />
      <Drawer
        title={isEditMode ? '订单详情' : '添加订单'}
        width={800}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={ (currentRow?.orderStatus === 0 && currentRow?.payType === '2' ) ?    <Popconfirm key="audit" title="请确认订单是否到账" onConfirm={() => handleAudit(currentRow.id)}>
        <Button  type='primary' >审核</Button>
      </Popconfirm> : false}
      >
        <OrderForm
          initialValues={currentRow}
          isEditMode={isEditMode}
          onClose={handleDrawerClose}
          handleAudit={handleAudit}
          onSuccess={() => actionRef.current?.reload()}
        />
      </Drawer>
    </PageContainer>
  );
};

export default OrderList;